import React from "react";
import { Form, Input, Button, message } from "antd";
import { LoginApi } from "./services";
import { useNavigate, Navigate } from "react-router-dom";
import "./index.css";

function Login() {
  const [form] = Form.useForm();
  const navigator = useNavigate();

  //在登陆状态下，需要跳转到home页面
  if (localStorage.getItem("token")) {
    return <Navigate to="/home" />;
  }
  const handleSubmit = (val) => {
    // 登录平台
    console.log("zhixng", val);
    if (!val.password || !val.username) {
      return message.warning("请输入用户名或者密码");
    }
    LoginApi(val).then((res) => {
      if (res.code == 200) {
        const { data } = res;
        localStorage.setItem("token", data.data.token);
        navigator("/home");
      } else {
        message.error("请输入正确的用户名或者密码");
      }
    });
  };

  return (
    <Form className="login-box" onFinish={handleSubmit}>
      <div className="title">系统登录</div>
      <Form.Item label="账号" name="username" rules={[{ required: true, message: "Please input your username!" }]}>
        <Input placeholder="请输入账号"></Input>
      </Form.Item>
      <Form.Item label="密码" name="password" rules={[{ required: true, message: "Please input your password!" }]}>
        <Input.Password placeholder="请输入密码" />
      </Form.Item>
      <Form.Item className="login-button">
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
}

export default Login;
